from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from extensions import db
import sqlalchemy as sa

# 用户收藏表，建立用户与其收藏新闻多对多的关系
tb_user_collection = db.Table(
    "forum_user_collection",
    db.Column("user_id", db.Integer, db.ForeignKey("forum_user.id"), primary_key=True),  # 新闻编号
    db.Column("article_id", db.Integer, db.ForeignKey("forum_article.id"), primary_key=True),  # 分类编号
    db.Column("create_at", db.DateTime, default=datetime.now)  # 收藏创建时间
)

# 用户关注表，记录用户关注的信息
tb_user_follows = db.Table(
    "forum_user_fans",
    db.Column('follower_id', db.Integer, db.ForeignKey('forum_user.id'), primary_key=True),  # 粉丝id
    db.Column('followed_id', db.Integer, db.ForeignKey('forum_user.id'), primary_key=True)  # 被关注人的id
)


class UserORM(db.Model):
    """用户"""
    __tablename__ = "forum_user"

    create_at = sa.Column(sa.DateTime, default=datetime.now)  # 记录的创建时间
    update_at = sa.Column(sa.DateTime, default=datetime.now, onupdate=datetime.now)  # 记录的更新时间

    id = sa.Column(sa.Integer, primary_key=True)  # 用户编号
    nick_name = sa.Column(sa.String(32), unique=False, nullable=False)  # 用户昵称
    password_hash = sa.Column(sa.String(128), nullable=False)  # 加密的密码
    mobile = sa.Column(sa.String(11), unique=True)  # 手机号
    email = sa.Column(sa.String(50), unique=True)  # 用户头像路径
    avatar_url = sa.Column(sa.String(256))  # 用户头像路径
    last_login = sa.Column(sa.DateTime, default=datetime.now)  # 最后一次登录时间
    is_admin = sa.Column(sa.Boolean, default=False)
    signature = sa.Column(sa.String(512))  # 用户签名

    gender = sa.Column(sa.Enum("M", "W"), default="M")
    is_enable = sa.Column(sa.Integer, default=0)

    collection_article_list = db.relationship("ArticleORM", secondary=tb_user_collection, lazy="dynamic")  # 用户收藏的新闻
    # 用户所有的粉丝，添加了反向引用 followed ，代表用户都关注了哪些人
    follower_list = db.relationship('UserORM',
                                    secondary=tb_user_follows,
                                    primaryjoin=id == tb_user_follows.c.followed_id,
                                    secondaryjoin=id == tb_user_follows.c.follower_id,
                                    backref=db.backref('followed', lazy='dynamic'),
                                    lazy='dynamic')

    # 当前用户所发布的新闻
    article_list = db.relationship('ArticleORM', backref='user', lazy='dynamic')

    # 当前用户的所有评论
    comment_list = db.relationship('CommentORM', backref='user', lazy='dynamic')

    # 当前用户所有点赞
    comment_like_list = db.relationship('CommentLikeORM', backref='user', lazy='dynamic')

    # 密文处理
    @property
    def password(self):
        raise Exception('密码不能返回')

    @password.setter
    def password(self, new):
        self.password_hash = generate_password_hash(new)

    def check_passwd(self, password):
        return check_password_hash(self.password_hash, password)

    def save(self):
        db.session.add(self)
        db.session.commit()

    def to_dict(self):
        return {
            'id': self.id,
            'nick_name': self.nick_name,
            # 'password_hash': self.password_hash,
            'mobile': self.mobile,
            'email': self.email,
            'avatar_url': self.avatar_url,
            'last_login': self.last_login.strftime('%Y-%m-%d %H:%M:%S'),
            # 'is_admin': self.is_admin,
            # 'signature': self.signature,
            'gender': self.gender,
            'create_at': self.create_at.strftime('%Y-%m-%d'),
            'enable': self.is_enable
        }
